/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/******************************************************************************
 * SVNVersionInformation:
 * ---------------------
 * $LastChangedRevision$
 * $LastChangedBy$
 * $LastChangedDate$
 * $HeadURL$
 ******************************************************************************/
package de.hft_stuttgart.botwar.common.models;

import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 *
 * @author pmv-mail@gmx.de
 */
public class Password implements Serializable {
    private byte[] password = new byte[1];

    /**
     * creates a md5 hash
     * @param pwd the string to be encrypted
     * @throws java.security.NoSuchAlgorithmException if the md5 algorithm
     * is not found.
     * @throws java.lang.IllegalArgumentException if the pwd is NULL or
     * shorter then 5 digits
     */
    public Password(final String pwd)
                    throws NoSuchAlgorithmException, IllegalArgumentException {
        if (pwd == null){
            throw new IllegalArgumentException("Password can't be NULL");
        }

        if (pwd.length() < 5) {
            throw new IllegalArgumentException(
                                        "Password to short! (under 5 chars)");
        }

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.reset();
        password = md5.digest(pwd.getBytes());
    }

    /**
     * Overrides method equals()
     * @param obj to compare
     * @return boolean true or false
     */
    @Override
    public boolean equals(final Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        Password pwd = (Password) obj;
        if (this.password.length != pwd.password.length){
            return false;
        }

        for (int i = 0; i < password.length; i++){
            if (this.password[i] != pwd.password[i]){
                return false;
            }
        }
        return true;
    }

    /**
     * Overrides method hashCode
     * @return hash code
     */
    @Override
    public int hashCode() {
        int hash = 2;
        hash = 7 * hash + Arrays.hashCode(this.password);
        return hash;
    }

    /**
     * Overrides method toString.
     * @return Text representation of this instance.
     */
    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < password.length; i++) {
            buffer.append(Integer.toHexString(0xFF & password[i]));
        }
        return buffer.toString();
    }

    /**
     *
     * @return length of the saved byte array
     */
    public int length() {
        return password.length;
    }

}
